import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';

import { CompactType, DisplayGrid, Gridster, GridsterConfig, GridsterItemConfig, GridsterItem, GridType } from 'angular-gridster2';
import { MarkdownModule } from 'ngx-markdown';
import { TrackByItem } from './track-by-item';

@Component({
  selector: 'app-track-by',
  templateUrl: './track-by.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  imports: [MatButtonModule, MatIconModule, MarkdownModule, Gridster, GridsterItem, TrackByItem]
})
export class TrackBy {
  options: GridsterConfig = {
    gridType: GridType.Fit,
    displayGrid: DisplayGrid.Always,
    compactType: CompactType.None,
    pushItems: true,
    draggable: {
      enabled: true
    },
    resizable: {
      enabled: true
    },
    minCols: 1,
    maxCols: 100,
    minRows: 1,
    maxRows: 100,
    maxItemCols: 100,
    minItemCols: 1,
    maxItemRows: 100,
    minItemRows: 1,
    maxItemArea: 2500,
    minItemArea: 1,
    defaultItemCols: 1,
    defaultItemRows: 1
  };
  dashboard: GridsterItemConfig[] = [
    {
      cols: 2,
      rows: 1,
      y: 0,
      x: 0,
      initCallback: TrackBy.itemInit,
      minItemCols: 1,
      maxItemCols: 100,
      maxItemRows: 100,
      minItemRows: 1,
      minItemArea: 1,
      maxItemArea: 2500,
      dragEnabled: true,
      resizeEnabled: true,
      compactEnabled: true,
      id: 0
    },
    { cols: 2, rows: 2, y: 0, x: 2, id: 1 },
    { cols: 1, rows: 1, y: 0, x: 4, id: 2 },
    { cols: 3, rows: 2, y: 1, x: 4, id: 3 },
    { cols: 1, rows: 1, y: 2, x: 1, id: 4 }
  ];
  dashboardOriginal: GridsterItemConfig[] = this.dashboard.map(x => ({ ...x }));

  static itemInit(item: GridsterItemConfig, itemComponent: GridsterItem): void {
    console.info('itemInitialized', item, itemComponent);
  }

  reset(): void {
    this.dashboard = this.dashboardOriginal.map(x => ({ ...x }));
  }

  addItem(): void {
    this.dashboard.push({
      x: 0,
      y: 0,
      cols: 1,
      rows: 1,
      id: this.dashboard.at(-1)?.id + 1
    });
  }

  removeItem($event: MouseEvent | TouchEvent, item: GridsterItemConfig): void {
    $event.preventDefault();
    $event.stopPropagation();
    this.dashboard.splice(this.dashboard.indexOf(item), 1);
  }
}
